package com.dy.yunying.biz.service.datacenter.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.dy.yunying.api.datacenter.dto.AdDataDto;
import com.dy.yunying.api.datacenter.dto.AdRecoveryDto;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.req.ChannelManageReq;
import com.dy.yunying.api.datacenter.vo.AdRecoveryVo;
import com.dy.yunying.api.vo.ChannelManageVo;
import com.dy.yunying.biz.dao.datacenter.impl.AdRecoveryDao;
import com.dy.yunying.biz.service.datacenter.AdRecoveryService;
import com.dy.yunying.biz.service.manage.*;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.feign.RemoteAccountService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：lile
 * @date ：2021/6/22 11:01
 * @description：
 * @modified By：
 */
@Log4j2
@Service(value = "dcAdRecoveryServiceImpl")
public class AdRecoveryServiceImpl implements AdRecoveryService {

	@Autowired
	private AdRecoveryDao adRecoveryDaoNew;

	@Autowired
	private AdRoleUserService adRoleUserService;

	@Autowired
	private RemoteAccountService remoteAccountService;

	@Autowired
	private ParentGameService parentGameService;

	@Autowired
	private ChannelManageService channelManageService;

	@Autowired
	private GameChannelPackService gameChannelPackService;

	@Autowired
	private GameService gameService;


	@Override
	public R selectAdRecoverySource(AdRecoveryDto req) {
		this.managerParam(req);

		List<AdRecoveryVo> resultData = adRecoveryDaoNew.selectAdRecoverySource(req); // 查询数据
		deal(resultData);

		return R.ok(resultData);
	}

	@Override
	public R countDataTotal(AdRecoveryDto req) {
		Long count = null;
		try {
			this.managerParam(req);

			count = adRecoveryDaoNew.countDataTotal(req);
		} catch (Exception e) {
			log.error("countDataTotal:[{}]", e);
			return R.failed("回收分析报表总记录数查询失败");
		}
		return R.ok(count);
	}

	private void managerParam(AdRecoveryDto req){
		// 判断是否管理员
		if (SecurityUtils.getRoles().contains(1)) {
			req.setIsSys(1);
		}else{
			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			roleUserIdList.addAll(ownerRoleUserIds);

			// 授权的广告账户
			List<String> roleAdAccountList = new ArrayList<>();
			req.setRoleAdAccountList(roleAdAccountList);
			final List<String> accountList2 = adRoleUserService.getThrowAccountList();
			if (ObjectUtils.isNotEmpty(accountList2)) {
				roleAdAccountList.addAll(accountList2);
			}
		}
	}

	private void deal(List<AdRecoveryVo> adRecoveryVos) {
		if (CollectionUtils.isNotEmpty(adRecoveryVos)) {

			//主渠道编码
			Map<String, String> map = new HashMap<>();
			ChannelManageReq req = new ChannelManageReq();
			req.setSize(99999L);
			IPage<ChannelManageVo> data = channelManageService.queryParentchlList(req);
			if (CollectionUtils.isNotEmpty(data.getRecords())) {
				List<ChannelManageVo> list = data.getRecords();
				map = list.stream().collect(Collectors.toMap(
						o -> {
							return String.valueOf(o.getChncode());
						}, ChannelManageVo::getChnname));
			}
			Map<String, String> finalMap = map;

			//分包编码名称
			List<String> appChlArr = new ArrayList<>();
			if (ObjectUtils.isNotEmpty(adRecoveryVos)) {
				adRecoveryVos.forEach(dataAccount -> {
					String appchl = dataAccount.getAppchl();
					if (StringUtils.isNotBlank(appchl)) {
						appChlArr.add(appchl);
					}
				});
			}
			List<String> distinctValue = appChlArr.stream().distinct().collect(Collectors.toList());
			List<Map<String, String>> appChlArrList = gameChannelPackService.queryAppChlName(distinctValue);
			Map<String, String> mapappChl = new HashMap<>();
			if (ObjectUtils.isNotEmpty(appChlArrList)) {
				appChlArrList.forEach(appChlData -> {
					mapappChl.put(String.valueOf(appChlData.get("code")), appChlData.get("codeName"));
				});
			}

			//封装数据
			for (AdRecoveryVo adRecoveryVo : adRecoveryVos) {
				try {
					final Long pgid = adRecoveryVo.getPgid();

					final Long gameid = adRecoveryVo.getGameid();

					final ParentGameDO parentGameDO = parentGameService.getByPK(pgid);
					String parentGameName = "-";
					if (parentGameDO != null) {
						parentGameName = parentGameDO.getGname();
					}
					adRecoveryVo.setParentGameName(parentGameName);


					final WanGameDO wanGameDO = gameService.selectVOByPK(gameid);
					String gameName = "-";
					if (wanGameDO != null) {
						gameName = wanGameDO.getGname();
					}
					adRecoveryVo.setGname(gameName);

					// 主渠道编码
					String parentchl = adRecoveryVo.getParentchl();
					adRecoveryVo.setParentchlName(finalMap.get(parentchl) == null ? parentchl : finalMap.get(parentchl));

					// 分包编码名称
					String appchl = adRecoveryVo.getAppchl();
					adRecoveryVo.setAppchl(mapappChl.get(appchl) == null ? appchl : mapappChl.get(appchl));

				} catch (Exception e) {
					log.error("数据处理异常", e);
				}
			}
		}
	}
}
